import requests
import json
import random
import os
import time
import traceback
class LiliBot():
    key='2c6a58deebc9e7883137d06a21ecbe85'
    secret='jz9p5qhmaoa6'
    apiurl='http://i.itpk.cn/api.php'
    pc_headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Cookie': 'PHPSESSID = gjo5rgahl1bmaju2872oga4552;user_check = MGI0Y2EyMzZmNDU2ZWQzZDIzNTQwYWVlMTAzN2YxZmE%3D',
        # 'Host': 'itpk.cn',
        'Referer': 'http://itpk.cn/robot.php',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
    }
    def get_message(self,keyword):
        try:
            url=self.apiurl+'?question='+keyword+self.get_param()
            r=requests.get(url,headers=self.pc_headers)
            return  r.text
        except Exception as e:
            return '尼古拉斯-赵四，没听懂你在说什么！'
    def get_param(self):
        return '&api_key='+self.key+'&api_secret='+self.secret
    def get_img(self,keyword):
        try:

            del self.pc_headers['Referer']
            self.pc_headers['Cookie']='__cfduid=db004a3c6f1685c7fe5a9043bf0985c4a1561622541; XSRF-TOKEN=eyJpdiI6Ijh4bGtDXC9FcGp0bUQzTXNqRWhNSm9BPT0iLCJ2YWx1ZSI6IjJVNTNpYlNVU0dicXA5TnhSVzhVK016S2phajZuT0xGaXkzeDJTbEVHUGN0WkI3U0MyTmlVKzRiY1huWlpDVSsiLCJtYWMiOiI5YWMxNzQzZmIwZmMwNGVkY2ZjZjg1NmI2MzJhMWE4ZmMxZDI1YTkxODUwMmVmYWJkNDc4M2QxYjQzYzE5OWFlIn0%3D; doutula_session=eyJpdiI6ImxnU1NMUmdmTng3dFNtb1hLSTI1MXc9PSIsInZhbHVlIjoiY3pXRTF6MXVxNHpXTmhBZXVsNDZIRU4xbFBYSStWdmNmV1NmY1RaWVNwSm9WaVlwRGtDQmpGRlJsakt4XC9VU3oiLCJtYWMiOiIxNDFkMzk3YmYyYjg0ZWQ3MTdmMmZjZjlmMjcwZTMzZjA4ZmIxMTk4Yjk0NDM1N2IyMWUxZTZhMWFiMmI5YTE4In0%3D'
            imgurl='https://www.doutula.com/api/search?keyword='+keyword+'&mime=0&page=2'
            r=requests.get(imgurl,headers=self.pc_headers)
            data=r.json()
            count=len(data['data']['list'])
            if count >0 :
                index=random.randrange(0,count)
                im_u=data['data']['list'][index]['image_url']
                surprifix=im_u[-3:]
                if surprifix in ['jpg','png','jpeg']:
                    return [im_u,True]
                else:
                    return [im_u,False]
        except Exception as e:
            print(traceback.print_exc())
            return ['http://ww2.sinaimg.cn/large/9150e4e5gw1fbsh1gurdcj206l04mq2v.jpg',True]

    def save_img(self,img_url,file_path='img'):
        # 保存图片到磁盘文件夹 file_path中，默认为当前脚本运行目录下的 book\img文件夹
        try:

            if not os.path.exists(file_path):
                print ('文件夹', file_path, '不存在，重新建立')

                # os.mkdir(file_path)
                os.makedirs(file_path)
            # 获得图片后缀
            # file_suffix = os.path.splitext(img_url)[1]
            file_suffix = '.jpg'
            # 拼接图片名（包含路径）
            t=time.time()
            filename = '{}{}{}{}'.format('', time.strftime("%Y-%m-%d_", time.localtime()) ,t, file_suffix)
            # print(filename)
            # exit()
            # 下载图片，并保存到文件夹中
            r = requests.get(img_url)
            with open('./img/'+filename, 'wb') as f:
                f.write(r.content)
            return  filename
        except IOError as e:
            print('文件操作失败', e)
            return ''

        except Exception as e:
            print ('错误 ：', e)
            return ''

if __name__ == '__main__':
    tuling=LiliBot()
    hot = ['王宝强', '了不起', '很牛', '浪起来', '心情倍爽']
    print(random.randrange(0, len(hot)))
    # exit()
    r = tuling.get_img(hot[random.randint(0, len(hot))])
    print(r)
    # print(tuling.get_message('消息'))
    # tuling.get_img('我的天')
    # tuling.save_img('http://ww2.sinaimg.cn/large/9150e4e5gy1fycvt6q744g20460460sp.gif')
    pass
